package Test.offer;

/**
 * @ClassName P56
 * @Description
 * @Company inspur
 * @Author Kevin
 * @Date 2020/8/3 10:25
 * @Version 1.0
 */
public class P56 {
    /**
     * 只出现一次的两个数字
     */
    public void findNumsApperOnce(int[] arr, int[] num1, int[] num2) {
        if (arr == null || arr.length < 2) {
            return;
        }
        //1.生成异或结果
        int res = arr[0];
        for (int i = 1; i < arr.length; i++) {
            res ^= arr[i];
        }
        //找到第一个为1的位
        int indexOf1 = 0;
        while ((res & 1) == 0 && (indexOf1 < 4 * 8)) {
            res = res >> 1;
            indexOf1++;
        }
        //对每个数组元素判断后分别异或
        num1[0] = 0;
        num2[0] = 0;
        for (int num: arr) {
            if(isBits(num, indexOf1) == 1) {
                num1[0] ^= num;
            } else {
                num2[0] ^= num;
            }
        }
    }

    int isBits(int num, int indexOf1) {
        num = num >> indexOf1;
        return (num & 1);
    }

    /**
     * 找出重复出现3次的元素
     */
    public int singleNumber(int[] nums) {
        int ones = 0;
        int twos = 0;

        for(int num: nums) {
            ones = ones ^ num & ~twos;
            twos = twos ^ num & ~ones;
        }
        return ones;
    }
}
